package com.ww.aviator.func;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.FunctionMissing;
import com.googlecode.aviator.runtime.JavaMethodReflectionFunctionMissing;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;

import java.util.Arrays;
import java.util.Map;

public class FunctionMissingExample {

    private static class TestFunctionMissing implements FunctionMissing {

        @Override
        public AviatorObject onFunctionMissing(String name, Map<String, Object> env, AviatorObject... args) {
            System.out.println("函数没找到, name=" + name + "\nenv=" + env + "\nargs=" + Arrays.toString(args));
            return FunctionUtils.wrapReturn(name);
        }
    }

    public static void main(String[] args) {
        AviatorEvaluator.setFunctionMissing(new TestFunctionMissing());

        System.out.println(AviatorEvaluator.execute("test(1,2,3)"));
        System.out.println(AviatorEvaluator.execute("not_found(1, 2, 3)"));

        System.out.println("=====================================");

        AviatorEvaluator.setFunctionMissing(JavaMethodReflectionFunctionMissing.getInstance());
        // 调用String#indexOf
        System.out.println(AviatorEvaluator.execute("indexOf('hello world', 'w')"));
        // 调用Long#floatValue
        System.out.println(AviatorEvaluator.execute("floatValue(3)"));
        // 调用BigDecimal#add
        System.out.println(AviatorEvaluator.execute("add(3M, 4M)"));
    }
}
